package com.fjzx.frame.viewmodel;

import android.arch.lifecycle.LiveData;
import android.arch.paging.PagedList;

import com.fjzx.androidframe.network.BaseLiveData;
import com.fjzx.androidframe.network.BaseViewModel;
import com.fjzx.androidframe.network.PagedNetworkDataSourceFactory;
import com.fjzx.androidframe.network.RepoManager;
import com.fjzx.androidframe.network.callback.PagedCallback;
import com.fjzx.frame.constant.Actions;
import com.fjzx.frame.entity.BaseResponse;
import com.fjzx.frame.entity.HomeEntity;
import com.fjzx.frame.entity.HomeResponse;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author xiongyongcong
 */
public class HomeViewModel extends BaseViewModel {
    public final BaseLiveData<String> homeArticalLiveData = new BaseLiveData<>(Actions.ACTION_GET_HOME_ARTICLE);
    private DataRepo repo;

    public HomeViewModel() {
        repo = RepoManager.ins().getRepo(DataRepo.class);
    }

    public LiveData<PagedList<HomeEntity>> getHomeArticals() {
        homeArticalLiveData.loading();
        return new PagedNetworkDataSourceFactory<HomeEntity>() {
            @Override
            public void load(int page, PagedCallback<HomeEntity> callback) {
                repo.getHomeArticles(page, new Callback<BaseResponse<HomeResponse>>() {
                    @Override
                    public void onResponse(Call<BaseResponse<HomeResponse>> call, Response<BaseResponse<HomeResponse>> response) {
                        List<HomeEntity> entities = response.body().getData().getDatas();
                        callback.onResult(entities);
                        homeArticalLiveData.success("");
                    }

                    @Override
                    public void onFailure(Call<BaseResponse<HomeResponse>> call, Throwable t) {
                        homeArticalLiveData.error(t.getMessage());
                    }
                });
            }
        }.build();
    }
}
